#include<stdio.h>
#include<stdlib.h>
#include<windows.h>
#include<conio.h>
//全局变量
int high,width;//游戏画面尺寸 
int ball_x,ball_y;//小球的坐标
int ball_vx,ball_vy;//小球的速度 
int  board_x,board_y;//挡板中心坐标 
int R;//挡板半径大小
int left,right;//挡板得左右边界 
int ball_number;
int score;//先砖块分数 
int brick_x,brick_y;//砖块坐标 




int gotoxy(int x,int y)//光标移动到（x，y） 位置 
{
	HANDLE handle = GetStdHandle (STD_OUTPUT_HANDLE);
	COORD pos;
	pos.X = x;
	pos.Y = y;
	SetConsoleCursorPosition (handle, pos);
} 



int hide()//隐藏光标 
{
	CONSOLE_CURSOR_INFO cursor_info = {1, 0};
	SetConsoleCursorInfo (GetStdHandle (STD_OUTPUT_HANDLE), &cursor_info);
} 





int starup()//游戏初始化 
{
	high = 20;
	width = 10;	
	
	ball_x = 10;
	ball_y = width/2;	
	 
	ball_vx = 1;
	ball_vy	= 1;
	
	board_x=high;
	board_y=width/2;
	R=5;
	left=board_y-R;
	right=board_y+R;
	
	ball_number=0;
	
	brick_x=0;
	brick_y=rand()%width;
}





int show()//游戏显示
{
	gotoxy(0,0); 
	hide();
	int i,j;
	for (i=0;i<=high+1;i++)
	{
		for (j=0;j<=width;j++)
		{
			if (i==ball_x&&j==ball_y)	//输出小球
				printf("O");
			else if((i==brick_x)&&(j==brick_y))
				printf("N");
			else if(j==width)
				printf("|");    //右边界 
			else if(i==high+1)
				printf("-");    //下边界 
			else if((i==high)&&(j>=left&&j<=right))
				printf("*");    //输出挡板 
			else 
				printf(" ");
		}
		printf("\n");
	}
	printf("反弹小球数:%d\n",ball_number);
	printf("得分：%d",score); 
}





int updataWithoutInput()//用户无关设置
{
	if((ball_x==brick_x)&&(ball_y==brick_y))  //小球消砖块时，砖块刷新 
	{
		ball_x=-ball_x;
		score++;
		brick_y=rand()%width;
		brick_x=0;
	}
	
	
	
	
	
	if(ball_x==high-1)                //小球没被接到时游戏结束 
	{
		if(ball_y>=left&&ball_y<=right)
		{
			ball_number++;
		//	ball_vy = -ball_vy;
		}
		else
		{ 
			printf("Game Over!");
			exit(0);
		}
	}
	
	ball_x = ball_x + ball_vx;
	ball_y = ball_y + ball_vy;
	
	//碰到边界后反弹
	if (ball_x == 0 || ball_x == high-1)
		ball_vx = -ball_vx; 
	if (ball_y == 0 || ball_y == width-1)
		ball_vy = -ball_vy;
		
	Sleep(50);
}





int updataWithInput()//用户有关设置
{
	char input;
	if(kbhit())//当按下键时执行
	{
		input=getch();
		if(input=='a')
		{
			board_y--;
			left=board_y-R;
			right=board_y+R;
		}
		if(input=='d')
		{
			board_y++;
			left=board_y-R;
			right=board_y+R;
		}
	} 
}




int main()
{
	starup();		//数据初始化 
	while(1)
	{
	
	
		show();		//显示画面 
	
		updataWithoutInput();		//与用户输入无关的更新 
	
		updataWithInput();		//与用户输入有关的更新 
	
	
	}	

	
	return 0;
}